﻿using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PSTFSInteg
{
    public partial class MainForm : Form
    {
        string SelectedCollection;

        public MainForm()
        {
            InitializeComponent();
            Environment.CurrentDirectory = ConfigurationManager.AppSettings["TFSAdminEXEDirectory"];
            lblTFS.Text = "TFS Server URL: " + ConfigurationManager.AppSettings["TFSServerURL"];
            this.GridMappedCollections.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.GridMappedCollections_CellClick);
            this.GridMappedProjects.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.GridMappedProjects_CellClick);
            this.BuildGridBtnColumns();
            this.GetMappedCollectionsIntoGrid();
            MappedWI.Text = ConfigurationManager.AppSettings["MappedWorkItems"];
        }

        private void BuildGridBtnColumns()
        {
            DataGridViewButtonColumn GetCollectionMappedProjects = new DataGridViewButtonColumn();
            {
                GetCollectionMappedProjects.HeaderText = "Get Mapped Projects";
               
                GetCollectionMappedProjects.Text = "Get Mapped Projects";
                GetCollectionMappedProjects.Width = 150;
                GetCollectionMappedProjects.UseColumnTextForButtonValue = true;
                GetCollectionMappedProjects.FlatStyle = FlatStyle.Standard;
                GetCollectionMappedProjects.DisplayIndex = 2;
            }
            GridMappedCollections.Columns.Add(GetCollectionMappedProjects);

            DataGridViewButtonColumn GetMappedWIT = new DataGridViewButtonColumn();
            {
                GetMappedWIT.HeaderText = "Mapped WIT";
                GetMappedWIT.Text = "Mapped WIT";
                GetMappedWIT.Width = 100;
                GetMappedWIT.UseColumnTextForButtonValue = true;
                GetMappedWIT.FlatStyle = FlatStyle.Standard;
                GetMappedWIT.DisplayIndex = 2;
            }
            GridMappedProjects.Columns.Add(GetMappedWIT);


            DataGridViewButtonColumn UnMapp = new DataGridViewButtonColumn();
            {
                UnMapp.HeaderText = "UnMapp";
                UnMapp.Text = "UnMapp";
                UnMapp.Width = 100;
                UnMapp.UseColumnTextForButtonValue = true;
                UnMapp.FlatStyle = FlatStyle.Standard;
                UnMapp.DisplayIndex = 3;
            }
            GridMappedProjects.Columns.Add(UnMapp);

            DataGridViewButtonColumn ForceUnMapp = new DataGridViewButtonColumn();
            {
                ForceUnMapp.HeaderText = "Force UnMapp";
                ForceUnMapp.Text = "Force UnMapp";
                ForceUnMapp.Width = 100;
                ForceUnMapp.UseColumnTextForButtonValue = true;
                ForceUnMapp.FlatStyle = FlatStyle.Standard;
                ForceUnMapp.DisplayIndex = 4;
            }
            GridMappedProjects.Columns.Add(ForceUnMapp);
        }

        private void GridMappedCollections_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                SelectedCollection = GridMappedCollections.Rows[e.RowIndex].Cells[0].Value.ToString();
                this.GetCollectionTeamProjects(SelectedCollection);
                lblMappedProjects.Text = "Collection: " + SelectedCollection;
                CollectionPanel.Enabled = true;

                string Result = this.ExecuteCommandSync("TfsAdmin ProjectServer /GetMappedProjects /Collection:" + GridMappedCollections.Rows[e.RowIndex].Cells[0].Value);
                Result = Result.IndexOf("Enterprise project ") > 0?  Result.Substring(Result.IndexOf("Enterprise project ")): String.Empty;
                String[] sepaerator = { "Enterprise project ", ".\r\n" };
                string[] MappedProjectss = Result.Split(sepaerator, 100, StringSplitOptions.RemoveEmptyEntries);

                List<MappedProject> GridResult = GridResult = new List<MappedProject>();
                string ProjectSplit = "is mapped to team project ";
                for (int i = 0; i < MappedProjectss.Length; i++)
                {                    
                    MappedProject item = new MappedProject
                        (MappedProjectss[i].Substring(MappedProjectss[i].IndexOf(ProjectSplit) + ProjectSplit.Length)
                        , MappedProjectss[i].Substring(0, MappedProjectss[i].IndexOf(ProjectSplit) - 1));
                    GridResult.Add(item);                    
                }
                GridMappedProjects.DataSource = GridResult;
            }
            catch (Exception ex)
            {
                this.HandelException(ex);
            }
        }

        private void GridMappedProjects_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex == 2) // GetMappedWorkItemTypes
                {
                    string Result = this.ExecuteCommandSync("TfsAdmin ProjectServer /GetMappedWorkItemTypes /Collection:" + SelectedCollection
                        + " /teamproject:\"" + GridMappedProjects.Rows[e.RowIndex].Cells[0].Value.ToString() + "\"");                    
                }
                else if (e.ColumnIndex == 3) // Unmap
                {
                    string Request = "TfsAdmin ProjectServer /UnmapPlanFromTeamProject /Collection:" + SelectedCollection
                        + " /teamproject:\"" + GridMappedProjects.Rows[e.RowIndex].Cells[0].Value.ToString()
                         + "\" /enterpriseProject:\"" + GridMappedProjects.Rows[e.RowIndex].Cells[1].Value.ToString();
                    string Result = this.ExecuteCommandSync(Request);
                    txtResult.Text = Result;
                    if (string.IsNullOrWhiteSpace(txtResultError.Text))
                        MessageBox.Show("Operation Completed Successfully...\r\nSelect \"Get Mapped Projects\" to get updated mapped projects ");
                }

                else if (e.ColumnIndex == 4) // Unmap Force
                {
                    string Request = "TfsAdmin ProjectServer /UnmapPlanFromTeamProject /Collection:" + SelectedCollection
                        + " /teamproject:\"" + GridMappedProjects.Rows[e.RowIndex].Cells[0].Value.ToString()
                         + "\" /enterpriseProject:\"" + GridMappedProjects.Rows[e.RowIndex].Cells[1].Value.ToString() + "\" /force";
                    string Result = this.ExecuteCommandSync(Request);
                    txtResult.Text = Result;
                    if (string.IsNullOrWhiteSpace(txtResultError.Text))
                        MessageBox.Show("Operation Completed Successfully...\r\nSelect \"Get Mapped Projects\" to get updated mapped projects ");
                }
            }
            catch (Exception ex)
            {
                this.HandelException(ex);
            }
        }

        private void GetMappedCollectionsIntoGrid()
        {
            try
            {
                string Result = this.ExecuteCommandSync("TfsAdmin ProjectServer /GetMappedCollections /tfs:" + ConfigurationManager.AppSettings["TFSServerURL"]);
                Result = Result.IndexOf("Collection ") > 0 ? Result.Substring(Result.IndexOf("Collection ")) : String.Empty;
                String[] sepaerator = { "Collection ", ".\r\n" };
                string[] MappedCollections = Result.Split(sepaerator, 100, StringSplitOptions.RemoveEmptyEntries);

                List<MappedCollection> GridResult = new List<MappedCollection>();
                string CollectionSplit = "is mapped to PWA ";
                for (int i = 0; i < MappedCollections.Length; i++)
                {
                    MappedCollection item = new MappedCollection
                        ( MappedCollections[i].Substring(0, MappedCollections[i].IndexOf(CollectionSplit) - 1)
                        ,MappedCollections[i].Substring(MappedCollections[i].IndexOf(CollectionSplit) + CollectionSplit.Length));
                    GridResult.Add(item);
                    
                }
                GridMappedCollections.DataSource = GridResult;
            }
            catch (Exception ex)
            {
                this.HandelException(ex);
            }
        }

        private void GetRegisteredPWA_Click(object sender, EventArgs e)
        {
            try
            {
                txtResult.Text = this.ExecuteCommandSync("TfsAdmin ProjectServer /GetRegisteredPWA /tfs:" + ConfigurationManager.AppSettings["TFSServerURL"]);
            }
            catch (Exception ex)
            {
                this.HandelException(ex);
            }
        }
     
        public string ExecuteCommandSync(string command)
        {
            Cursor.Current = Cursors.WaitCursor;

            txtCMDInput.Text = command;
            txtResultError.Text = "";
            txtResult.Text = "";
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();

            // The following commands are needed to redirect the standard output.
            // This means that it will be redirected to the Process.StandardOutput StreamReader.           
            startInfo.RedirectStandardOutput = true;
            startInfo.RedirectStandardError = true;
            startInfo.UseShellExecute = false;


            startInfo.CreateNoWindow = true;
            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

            startInfo.FileName = "cmd.exe";
            startInfo.Arguments = "/C " + command;
            process.StartInfo = startInfo;
            process.Start();
            txtResultError.Text = process.StandardError.ReadToEnd();

            string Result = process.StandardOutput.ReadToEnd();
            txtResult.Text = Result;
            Cursor.Current = Cursors.Default;

            return Result;
        }

        private void MapProject_Click(object sender, EventArgs e)
        {
            try
            {
                string Request = "TfsAdmin ProjectServer /mapplantoteamproject /Collection:" + SelectedCollection
                    + " /enterpriseproject:\"" + MAPPWAProject.Text + "\" /teamproject:\"" + MapTeamProject.Text
                    + "\"  /workitemtypes:\"" + MappedWI.Text + "\"";
                txtResult.Text = this.ExecuteCommandSync(Request);
                if (string.IsNullOrWhiteSpace(txtResultError.Text))
                    MessageBox.Show("Operation Completed Successfully...\r\nSelect \"Get Mapped Projects\" to get updated mapped projects ");
            }
            catch (Exception ex)
            {
                this.HandelException(ex);
            }
        }

        private void HandelException(Exception ex)
        {
            MessageBox.Show("Error:\r\n" + ex.Message + "\r\n" + ex.StackTrace);
        }

        private void GetCollectionTeamProjects(string Collection)
        {
            TfsTeamProjectCollection tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(Collection));
            ICommonStructureService css = (ICommonStructureService)tfs.GetService(typeof(ICommonStructureService));
            ProjectInfo [] CollectionProjects = css.ListAllProjects();
            MapTeamProject.Items.Clear();
            foreach (var item in CollectionProjects)
            {
                MapTeamProject.Items.Add(item.Name);
            }
        }
    }
}
